import sheep from '@/sheep';
// #ifdef H5
import $wxsdk from '@/sheep/libs/sdk-h5-weixin';
// #endif
import { getRootUrl } from '@/sheep/helper';

/**
 * 支付
 *
 * @param {String} payment = ['wechat']  	- 支付方式
 * @param {String} orderType = ['goods','groupon']  	- 订单类型
 * @param {String} orderSN					- 订单号
 */

export default class SheepPay {
  constructor(payment, orderType, orderSN, totalAmount) {
    this.payment = payment;
    this.orderSN = orderSN;
    this.orderType = orderType;
    this.totalAmount = totalAmount;
    this.payAction();
  }

  payAction() {
    const payAction = {
      WechatMiniProgram: {
        wechat: () => {
          this.wechatMiniProgramPay();
        },
      },
      H5: {
        wechat: () => {
          this.wechatWapPay();
        },
      },
    };
    return payAction[sheep.$platform.name][this.payment]();
  }

  // 预支付
  prepay(wechatType = 1) {
    return new Promise((resolve, reject) => {
      let data = {
        payId: this.orderSN,
        type: 2,
        wechatType,
      };
      sheep.$api.pay.prepay(data).then((res) => {
        res && resolve(res);
      });
    });
  }
  // #ifdef H5
  // 微信公众号JSSDK支付
  async wechatOfficialAccountPay() {
    let that = this;
    let data = await this.prepay(1);
    console.log('h5 jssdk支付');
    $wxsdk.wxpay(data, {
      success: () => {
        that.payResult('success');
      },
      cancel: () => {
        sheep.$helper.toast('支付已手动取消');
      },
      fail: () => {
        that.payResult('fail');
      },
    });
  }

  //浏览器微信H5支付
  async wechatWapPay() {
    const data = await this.prepay();

    const redirect_url = `${getRootUrl()}pages/pay/result?orderSN=${this.orderSN}&payment=${this.payment}`;
    location.href = `${data.pay_data.h5_url}&redirect_url=${encodeURIComponent(redirect_url)}`;
  }

  // 支付链接
  async redirectPay() {
    let data = await this.prepay();

    const redirect_url = `${getRootUrl()}pages/pay/result?orderSN=${this.orderSN}&payment=${this.payment}`;
    location.href = data.pay_data + encodeURIComponent(redirect_url);
  }

  // #endif

  // 微信小程序支付
  async wechatMiniProgramPay() {
    let that = this;
    let result = await this.prepay(2);

    uni.requestPayment({
      provider: 'wxpay',
      nonceStr: result.nonceStr,
      package: result.package_,
      paySign: result.paySign,
      signType: result.signType,
      timeStamp: result.timeStamp,
      success: (res) => {
        console.log('支付结果>>>' + res);
        that.payResult('success');
      },
      fail: (err) => {
        if (err.errMsg === 'requestPayment:fail cancel') {
          sheep.$helper.toast('支付已手动取消');
        } else {
          that.payResult('fail');
        }
      },
    });
  }

  // 支付结果跳转,success:成功，fail:失败
  payResult(resultType) {
    sheep.$router.redirect('/pages/pay/result', {
      orderSN: this.orderSN,
      payment: this.payment, //重新支付的时候使用
      payState: resultType,
      orderType: this.orderType,
    });
  }
}
